<?php
/*
 * @Description  : 公共文件
 * @Author       : https://github.com/skyselang
 * @Date         : 2020-04-16
 * @LastEditTime : 2021-03-23
 */

use think\facade\Config;
use think\facade\Db;
use think\facade\Request;
use app\admin\service\TokenService;

/**
 * 成功返回
 *
 * @param array   $data 成功数据
 * @param string  $msg  成功提示
 * @param integer $code 成功码
 * 
 * @return json
 */
function success($data = [], string $msg = '操作成功', int $code = 200)
{
    $res['code'] = $code;
    $res['msg']  = $msg;
    $res['data'] = $data;

    return json($res);
}

/**
 * 错误返回
 *
 * @param string  $msg  错误提示
 * @param array   $err  错误数据
 * @param integer $code 错误码
 * 
 * @return json
 */
function error(string $msg = '操作失败', $err = [], int $code = 400)
{
    $res['code'] = $code;
    $res['msg']  = $msg;
    $res['err']  = $err;

    print_r(json_encode($res, JSON_UNESCAPED_UNICODE));

    exit;
}

/**
 * 抛出异常
 *
 * @param string  $msg  异常提示
 * @param integer $code 错误码
 * 
 * @return json
 */
function exception(string $msg = '操作失败', int $code = 400)
{
    throw new \think\Exception($msg, $code);
}

/**
 * 服务器地址
 * 协议和域名
 *
 * @return string
 */
function server_url()
{
    if (isset($_SERVER['HTTPS']) && ('1' == $_SERVER['HTTPS'] || 'on' == strtolower($_SERVER['HTTPS']))) {
        $http = 'https://';
    } elseif (isset($_SERVER['SERVER_PORT']) && ('443' == $_SERVER['SERVER_PORT'])) {
        $http = 'https://';
    } else {
        $http = 'http://';
    }

    $host = $_SERVER['HTTP_HOST'];
    $res  = $http . $host;

    return $res;
}

/**
 * 文件地址
 * 协议，域名，文件路径
 *
 * @param string $file_path 文件路径
 * 
 * @return string
 */
function file_url($file_path = '')
{
    if (empty($file_path)) {
        return '';
    }

    if (strpos($file_path, 'http') !== false) {
        return $file_path;
    }

    $server_url = server_url();

    if (stripos($file_path, '/') === 0) {
        $res = $server_url . $file_path;
    } else {
        $res = $server_url . '/' . $file_path;
    }

    return $res;
}

/**
 * 获取请求pathinfo
 * 应用/控制器/操作 
 * eg：admin/Index/index
 *
 * @return string
 */
function request_pathinfo()
{
    $request_pathinfo = app('http')->getName() . '/' . Request::pathinfo();

    return $request_pathinfo;
}

/**
 * http get 请求
 *
 * @param string $url    请求地址
 * @param array  $header 请求头部
 *
 * @return array
 */
function http_get($url, $header = [])
{
    if (empty($header)) {
        $header = [
            "Content-type:application/json;",
            "Accept:application/json"
        ];
    }

    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
    $response = curl_exec($curl);
    curl_close($curl);
    $response = json_decode($response, true);

    return $response;
}

/**
 * http post 请求
 *
 * @param string $url    请求地址
 * @param array  $param  请求参数
 * @param array  $header 请求头部
 *
 * @return array
 */
function http_post($url, $param = [], $header = [])
{
    $param  = json_encode($param);

    if (empty($param)) {
        $header = [
            "Content-type:application/json;charset='utf-8'",
            "Accept:application/json"
        ];
    }

    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
    curl_setopt($curl, CURLOPT_POST, 1);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $param);
    curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    $response = curl_exec($curl);
    curl_close($curl);
    $response = json_decode($response, true);

    return $response;
}

/**
 * 获取用户id
 *
 * @return integer
 */
function user_id()
{
    $user_token = user_token();

    $user_id = TokenService::userId($user_token);

    return $user_id;
}

/**
 * 获取用户token
 *
 * @return string
 */
function user_token()
{
    $token_key  = Config::get('index.token_key');
    $user_token = Request::header($token_key, '');

    return $user_token;
}

/**
 * 获取当前日期时间
 * format：Y-m-d H:i:s
 *
 * @return string
 */
function datetime()
{
    return date('Y-m-d H:i:s');
}

/**
 * 去除字符串首尾字符
 * 
 * @param string $str  字符串
 * @param string $char 要去除的字符
 * 
 * @return string
 */
function str_trim($str, $char = ',')
{
    $str = trim($str, $char);

    return $str;
}

/**
 * 在字符串首尾拼接字符
 * 
 * @param string $str  字符串
 * @param string $char 要拼接的字符
 * 
 * @return string
 */
function str_join($str, $char = ',')
{
    $str = $char . $str . $char;

    return $str;
}

/**
 *
 * 生成MN
 * @param $enterprise_id
 * @return string
 */
//61012527093520120000
function generate_mn($enterprise_id)
{
    $time = time();
    $Mn = "610100"."".$time."".uniqid()."".$enterprise_id;
    return  $Mn;
}

/**
 * 生成设备编码
 * @return string
 */
function equipment_code()
{
    return "100000"."".uniqid();
}

/**
 * @param $arr   //递归数组
 * @param $id     //递归条件id
 * @return array
 */

function findChild(&$arr,$id){
    $childs=array();
    foreach ($arr as $k => $v){
        if($v['parent_id']== $id){
            $childs[]=$v;
        }
    }
    return $childs;
}

/**
 * @param $rows   //递归数组
 * @param $root_id   //顶级0
 * @return array|null
 */
function build_tree($rows,$root_id){
    $childs= findChild($rows,$root_id);
    if(empty($childs)){
        return null;
    }
    foreach ($childs as $k => $v){
        $rescurTree= build_tree($rows,$v['id']);
        if( null != $rescurTree){
            $childs[$k]['childs']=$rescurTree;
        }
    }
    return $childs;
}


function get_url($url)
{
    $host = $_SERVER['SERVER_NAME'];
   // http://47.118.56.88/uploads/photo/d0/42f66d43b5d6aa8bf259bd9cdd5b4c.png
    return "http://".$host.$url;
}

/**
 * 获取配置文件
 */
function get_config_one($type)
{
   $config_type = Db::name("enterprise_config") -> where(["id" => $type]) -> find();
   return $config_type;
}


/**
 * 获取时间
 * @param $type
 * @return array
 */
function time_slot($type){
    if ($type == 1){
        $begintime = mktime(0,0,0,date('m'),date('d'),date('Y'));
        $endtime = mktime(0,0,0,date('m'),date('d')+1,date('Y'))-1;
    }else if($type == 2){
        $begintime =  mktime(0,0,0,date('m'),date('d')-1,date('Y'));
        $endtime =  mktime(0,0,0,date('m'),date('d'),date('Y'))-1;
    }else if($type == 3){
        $begintime = mktime(0, 0 , 0,date("m"),date("d")-date("w")+1,date("Y"));
        $endtime = mktime(23,59,59,date("m"),date("d")-date("w")+7,date("Y"));
    }else if($type == 4){
        $begintime = mktime(0,0,0,date('m'),date('d')-date('w')+1-7,date('Y'));
        $endtime = mktime(23,59,59,date('m'),date('d')-date('w')+7-7,date('Y'));
    }else if($type == 5){
        $begintime = mktime(0,0,0,date('m'),1,date('Y'));
        $endtime = mktime(23,59,59,date('m'),date('t'),date('Y'));
    }else if($type == 6){
        $begintime = mktime(0, 0 , 0,date("m")-1,1,date("Y"));
        $endtime = mktime(23,59,59,date("m") ,0,date("Y"));
    }

    return [$begintime,$endtime];
}